import type {
  IRes,
  IResWithPage,
} from '../../types/api';
import type {
  IExam,
  IExamRecord,
  IExamWithPaper,
  IStartExamResponse,
} from '../../types/exam';
import request from '../httpRequest';

export interface GetExamListParams {
  page?: number;
  limit?: number;
}

export interface SaveExamAnswerRequest {
  exam_id: string;
  answers: Array<{
    question_id: string;
    selected_answers: number[];
  }>;
}

export interface SubmitExamRequest {
  record_id: string;
  answers: Array<{
    question_id: string;
    selected_answers: number[];
  }>;
  is_timeout?: boolean;
}

export interface GetExamRecordsParams {
  page?: number;
  limit?: number;
  status?: string;
}

export const examApi = {
  // 获取可参与的考试列表
  getExamList(params?: GetExamListParams): IRes<{
    list: IExam[];
    pagination: {
      total: number;
      page: number;
      limit: number;
      totalPages: number;
    };
  }> {
    return request.get('/exam/available', { params });
  },

  // 获取考试详情
  getExamDetail(id: string): IRes<IExamWithPaper> {
    console.log('getExamDetail API 调用:', { id, url: `/exam/${id}` })
    
    return request.get(`/exam/${id}`);
  },

  // 开始考试
  startExam(id: string): IRes<IStartExamResponse> {
    return request.post('/exam-record/start', { exam_id: id });
  },

  // 保存答案（自动保存）
  saveExamAnswer(data: SaveExamAnswerRequest): IRes<{
    saved: boolean;
    timestamp: number;
  }> {
    return request.post('/exam/saveAnswer', data);
  },

  // 提交考试记录
  submitExamRecord(data: SubmitExamRequest): IRes<{
    record_id: string;
    score: number;
    passed: boolean;
  }> {
    console.log('submitExamRecord API 调用:', {
      url: `/exam-record/${data.record_id}/submit`,
      method: 'put',
      data: {
        answers: data.answers,
        is_timeout: data.is_timeout
      }
    })
    
    return request.put(`/exam-record/${data.record_id}/submit`, {
      answers: data.answers,
      is_timeout: data.is_timeout
    });
  },

  // 获取考试结果
  getExamResult(recordId: string): IRes<{
    record: IExamRecord & {
      activity: IExam;
      score: number;
      ranking?: number;
      totalParticipants?: number;
    };
  }> {
    return request.get(`/exam-record/${recordId}`);
  },

  // 获取考试记录列表
  getExamRecords(params?: GetExamRecordsParams): IResWithPage<IExamRecord & {
    activity: Pick<IExam, '_id' | 'exam_name' | 'start_time' | 'end_time'>;
    score: number;
  }> {
    return request.get('/exam-record/list', { params });
  },

  // 获取考试记录详情
  getExamRecordDetail(recordId: string): IRes<{
    record: IExamRecord & {
      activity: IExam;
      questions: Array<{
        _id: string;
        content: string;
        type: string;
        options?: Array<{
          symbol: string;
          content: string;
        }>;
        answer: number[];
        score: number;
        user_answer: number[];
        is_correct: boolean;
      }>;
    };
  }> {
    return request.get('/exam/recordDetail', { params: { recordId } });
  },

  // 获取考试排名
  getExamRanking(examId: string): IRes<{
    rankings: Array<{
      user_id: string;
      username: string;
      score: number;
      total_score: number;
      rank: number;
      submit_time: string;
    }>;
  }> {
    return request.get(`/exam/${examId}/ranking`);
  }
}
